package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * cookie的生命周期
 */
public class C5_CookieLife extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("C5_CookieLife 被调用...");

        //创建一个cookie，生命周期为60s
        Cookie cookie = new Cookie("job", "java");
        //setMaxAge(60) 从创建该cookie开始计时，60s后就无效
        //浏览器来根据创建的时间开始计时，60s后就认为cookie无效
        //如果该cookie无效，那么浏览器在发出http请求时就不再携带该cookie
        //默认是-1 表示关闭浏览器就删除cookie(会话级别)
        //0表示马上删除cookie
        cookie.setMaxAge(60);

        resp.setContentType("text/html;charset=utf-8");
        resp.addCookie(cookie);
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>设置cookie生命周期成功</h1>");
        writer.flush();
        writer.close();

    }
}
